//
//  serviceInterfaceTemplate.m
//  aliAlbum
//
//  Created by xugaoqiang on 11-9-22.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "serviceInterfaceTemplate.h"

@implementation serviceInterfaceTemplate
@synthesize m_request;
@synthesize m_identity;
@synthesize m_dicSendData;
@synthesize m_dicReceiveData;

-(id)init
{
	self = [super init];
	if (self)
	{
		m_request = nil;
		m_dicSendData = nil;
		m_requestMode = Request_Mode_Asynchronous;// Default is asynchronous mode.
		m_dicReceiveData = nil;
		m_bEmptyDB = NO;
	}
	return self;
}

-(void)allOver
{
	if (nil != m_request)
	{
		[m_request cancel];
        m_request.delegate = nil;
	}
    self.m_serviceHandler = nil;
}

#pragma mark -
#pragma mark Service Configuration

-(void)setRequestMode:(TRequestMode)mode
{
	m_requestMode = mode;
}

#pragma mark -
#pragma mark Send Request
- (NSData*)encryptBodyData:(NSData*)bodyData
{
	return bodyData;
}

-(void)configureRequest
{
	[m_request setTimeOutSeconds:kTimeOutDuration]; // set time out duration
	[m_request setStringEncoding:NSASCIIStringEncoding];
	[m_request setDelegate:self];
}

-(void)sendRequest:(NSDictionary*)aDic
{
	@autoreleasepool {
        @synchronized(self)
        {
            self.m_dicSendData = nil;
            if (nil != aDic) m_dicSendData = aDic;
            
            [self send];
        }
    }
}

- (void) send
{
    self.m_dicReceiveData = nil;
	m_dicReceiveData = [[NSMutableDictionary alloc] init];
	NSData *dataProtobuf = nil;

	// 2. get url
	NSURL *anURL = [self targetURL];
	
	// 3. prepare request
	if (nil != m_request)
	{
		[m_request cancel];
        self.m_request = nil;
	}
	// Initialize the http engine (required)
	m_request = [[ASIFormDataRequest alloc] initWithURL:anURL];
	
	// 4. add body data
	if (nil != dataProtobuf) [m_request appendPostData:[self encryptBodyData:dataProtobuf]];
	
	// 5. configure the request
	[self configureRequest];
	
	// 6.start request
	switch (m_requestMode)
	{
		case Request_Mode_Synchronous:
		{
			[m_request startSynchronous];
			break;
		}
		default:
		{
			[m_request startAsynchronous];
			break;
		}
	}
}

#pragma mark -
#pragma mark ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    [GlobalInfo sharedInstance].errorCount = 0;
    
	NSData *dataResponse = [request responseData];

	[self parseResponseData:dataResponse];
    [self passDataOut];

	[self allOver];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSError *error = [request error];

    self.m_dicReceiveData = nil;
	m_dicReceiveData = [[NSMutableDictionary alloc] init];

    //屏蔽掉不需要返回的请求
    if([self isKindOfClass:NSClassFromString(@"serviceChangeVolume")] ||
       [self isKindOfClass:NSClassFromString(@"serviceChangeLanguage")] ||
       [self isKindOfClass:NSClassFromString(@"serviceHDMIOverScan")] ||
       [self isKindOfClass:NSClassFromString(@"servicePlaySeek")] ||
       [self isKindOfClass:NSClassFromString(@"serviceResetDevice")] ||
       [self isKindOfClass:NSClassFromString(@"serviceRebootDevice")] ||
       [self isKindOfClass:NSClassFromString(@"servicePlayControl")])
    {
        return;
    }
    
    [GlobalInfo sharedInstance].errorCount++;
    if([GlobalInfo sharedInstance].errorCount < 3)
    {
        [self send];
        return;
    }
    
	switch (error.code)
	{
		case ASIConnectionFailureErrorType:
		{
			[m_dicReceiveData setObject:SERVICE_CONNECTIONFAIL forKey:@"responsestatus"];
			break;
		}
		case ASIRequestTimedOutErrorType:
		{
			[m_dicReceiveData setObject:SERVICE_TIMEOUT forKey:@"responsestatus"];
			break;
		}
		default:
		{
			[m_dicReceiveData setObject:SERVICE_FAIL forKey:@"responsestatus"];
			break;
		}
	}
    
	[self requestDidFailed];
	
    [self passDataOut];
	NSLog(@"*** requestDidFailed %@",self.m_request.url);
	// end http cycle
	[self allOver];
}

- (void)requestDidFailed
{
	
}

#pragma mark -
#pragma mark Parse Response Data
- (void)parseResponseData:(NSData*)data
{
	int statusCode = [m_request responseStatusCode];
	
	if (200 == statusCode)
	{
		[m_dicReceiveData setObject:SERVICE_SUCCESS forKey:@"responsestatus"];
	}
	else if (500 == statusCode)
	{
		[m_dicReceiveData setObject:SERVICE_FAIL forKey:@"responsestatus"];
	}
	else
	{
		[m_dicReceiveData setObject:SERVICE_FAIL forKey:@"responsestatus"];
	}
}

#pragma mark -
#pragma mark Pass Data Out
- (void)passDataOut
{
}

-(void)clearData
{
    self.m_dicReceiveData = nil;
    self.m_dicSendData = nil;
}

@end
